<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="ID" prop="id">
            <el-input v-model="queryParams.id" placeholder="请输入ID" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <!--            <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>-->
          </el-col>
          <!--<el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
          </el-col>-->
          <el-col :span="1.5">
            <!--            <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['system:user:import']">导入</el-button>-->
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="id" />
          <el-table-column label="生成数量" align="center" prop="quantity" :show-overflow-tooltip="true" />
          <el-table-column label="时效(天)" align="center" prop="segment" :show-overflow-tooltip="true" />
          <el-table-column label="权限" align="center" prop="productIds" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              <span style="color: #1c84c6;cursor: pointer"
                    @click="getBatchInPermission(scope.row.id)">{{scope.row.productIds ? JSON.parse(scope.row.productIds).length : 0}}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="新增时间" align="center" prop="createTime" :show-overflow-tooltip="true" />
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="checkProductsNum(scope.row)">查看详情</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="remove(scope.row)">删除</el-button>
            <!--  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">编辑</el-button>
              <el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-check" @click="handleStatusChange(scope.row)">冻结</el-button>
              <el-button v-else size="mini" type="text" icon="el-icon-close" @click="handleStatusChange(scope.row)">激活</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col v-if="title !== '修改用户'" :span="24">
            <el-form-item label="创建方式" prop="operationType">
              <el-radio-group v-model="form.operationType">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="form.operationType === 'BATCH'" :span="24">
            <el-form-item label="创建用户个数" prop="batchUser">
              <el-input :type="form.operationType === 'BATCH' ? 'Number' : 'text'" min="0" v-model="form.batchUser" placeholder="请输入创建用户个数" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.operationType !== 'BATCH'" :span="24">
            <el-form-item label="用户名" prop="username">
              <el-input :disabled="title === '修改用户'" :type="form.operationType === 'BATCH' ? 'Number' : 'text'" v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="form.operationType !== 'BATCH'" :span="24">
            <el-form-item label="密码" prop="password">
              <el-input :type="form.operationType === 'BATCH' ? 'Number' : 'text'" v-model="form.password" placeholder="请输入密码" minlength="6" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="时效" prop="segment">
              <el-input type="Number" min="0" v-model="form.segment" placeholder="请输入时效时间" minlength="10" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="false" :span="24">
            <el-form-item label="主账户管理" prop="operateUsername">
              <el-input v-model="form.operateUsername" placeholder="请输入主账户管理" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开通权限" prop="productIds">
              <el-select v-model="form.productIds" multiple placeholder="请选择开通权限">
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="分配cookie" prop="codeIds">
              <el-select v-model="form.codeIds" multiple :placeholder="form.code">
                <el-option
                  v-for="item in productCookieList"
                  :key="item.id"
                  :label="item.code"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!--    根据权限数量查看具体权限-->
    <el-dialog
      title="查看详情"
      :visible.sync="productsDilog"
      >
      <el-form :model="Params" ref="queryFormDetail" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="Params.username" placeholder="请输入用户名称" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQueryDetail">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryDetail">重置</el-button>
          <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExportDetail(id)" v-hasPermi="['system:user:export']">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="productsList" @selection-change="handleSelectionChangeDetail">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="用户名" align="center" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="密码" align="center" prop="password" :show-overflow-tooltip="true" />
        <el-table-column label="是否使用" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.used ? '是' : '否'}}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="totalParams>0" :total="totalParams" :page.sync="Params.pageNum" :limit.sync="Params.pageSize" @pagination="checkProductsNum({id: id})" />
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="productsDilog = false">关 闭</el-button>
  </span>
    </el-dialog>

    <!--    根据权限数量查看具体权限-->
    <el-dialog
      title="包含权限"
      :visible.sync="permissionDilog"
      width="600px"
    >
      <el-table
        :data="permissionList"
        style="width: 100%">
        <el-table-column
          prop="productName"
          label="客户端名称"
          width="560px"
          align="center">
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="permissionDilog = false">关 闭</el-button>
  </span>
    </el-dialog>


  </div>
</template>

<script>
  import {
    exportUserDetail,
    listUser,
    getUser,
    delUser,
    addUser,
    updateUser,
    exportUser,
    resetUserPwd,
    changeUserStatus,
    importTemplate,
    chcekProductsNum,
    removeBatchUser,
    getPermissionList
  } from "@/api/system/generateUser/user";
  import {getCode} from "@/api/code"
  import { getToken } from "@/utils/auth";
  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import {listData} from "@/api/index/index"
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {getProducts} from "@/api/index/index"
  import { mapGetters } from "vuex"

  export default {
    name: "User",
    components: { Treeselect },
    data() {
      return {

        totalParams: 0,

        pickerOptions: {
          disabledDate(time) {
            return time.getTime() <= (Date.now()-(24 * 60 * 60 * 1000));
          }
        },

        // 查询参数
        Params: {
          pageNum: 1,
          pageSize: 10,
          username: ''
        },

        id: '',

        productsList: [],
        permissionList :[],

        productsDilog: false,
        permissionDilog: false,

        list: [],
        // 遮罩层
        loading: true,
        // 选中数组
        idsDetail: [],
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [
          {dictValue: 'SINGLE',
            dictLabel:'单个创建'
          },
          {dictValue: 'BATCH',
            dictLabel:'批量创建'
          }
        ],
        // 性别状态字典
        sexOptions: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {
          operationType: '',
          batchUser: 'SINGLE',
          username: '',
          password: '',
          segment: '',
          operateUsername: '',
          productIds: [],
          codeIds: [],
          code: '',
          remark:''
          // activationCode: ''
        },
        defaultProps: {
          children: "children",
          label: "label",
        },
        productCookieList:[],
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 提交loading
          submitLoading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          id: ''
        },
        // 表单校验
        rules: {
          operationType: [
            { required: true, message: "创建方式不能为空", trigger: "blur" },
          ],
          batchUser: [
            { required: true, message: "创建用户个数不能为空", trigger: "blur" },
          ],
          username: [
            { required: true, message: "用户名称不能为空", trigger: "blur" },
          ],
          password: [
            { required: true, message: "密码不能为空", trigger: "blur" },
          ],
          segment: [
            { required: true, message: "时效时间不能为空", trigger: "blur" },
          ],
          operateUsername: [
            { required: true, message: "用户名称不能为空", trigger: "blur" },
          ],
          productIds: [
            { required: true, message: "开头权限不能为空", trigger: "blur" },
          ],
          activationCode: [
            { required: true, message: "开头权限不能为空", trigger: "blur" },
          ],
        },
      };
    },
    computed: {
      ...mapGetters(['roles'])
    },

    created() {
      this.getListData()
      this.getList();
    },
    methods: {

      handleClose() {
      },

      //根据数量查看具体权限
      checkProductsNum(row) {
        this.id = row.id
        const batchId = row.batchId || row.id
        this.Params.id = batchId
        this.productsDilog = true
        chcekProductsNum(this.Params).then(resp => {
          let { code, rows, total } = resp
          if(code === 200) {
            this.productsList = rows
            this.totalParams = total
          }
        })
      },

      /**
       * 获取权限列表
       * */
      getBatchInPermission(batchId){
        this.permissionDilog = true
        getPermissionList(batchId)
          .then(resp => {
            let {data,code} = resp;
            if(code === 200){
              this.permissionList = data;
            }
          })
      },

      /** 查询用户列表 */
      getList() {
        this.loading = true;
        listUser(this.queryParams).then(
          (response) => {
            this.userList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status == "0" ? "冻结" : "激活";
        let status =  row.status == "0" ? "DISABLE" : "OK";
        this.$confirm(
          '确认要"' + text + '""' + row.username + '"用户吗?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return changeUserStatus(row.id, status);
          })
          .then(() => {
            this.msgSuccess(text + "成功");
            this.getList()
          })
          .catch(function () {
            row.status = row.status === "0" ? "1" : "0";
          });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          operationType: '',
          batchUser: '',
          username: '',
          password: '',
          segment: '',
          operateUsername: this.roles[0],
          productIds: [],
        };
        this.resetForm("form");
      },

      /** 查看详情搜索按钮操作 */
      handleQueryDetail() {
        this.Params.page = 1;
        this.checkProductsNum({id: this.id});
      },
      /** 查看详情重置按钮操作 */
      resetQueryDetail() {
        this.Params.username = ''
        this.resetForm("queryFormDetail");
        this.handleQueryDetail();
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 查看详情多选框选中数据
      handleSelectionChangeDetail(selection) {
        this.idsDetail = selection.map((item) => item.id);
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getProducts();
        this.open = true;
        this.submitLoading = false
        this.title = "添加用户";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();

        Object.keys(this.form).map(item => {
          if(item === 'productIds') {
            this.form[item] = []
          }else {
            this.form[item] = row[item]
          }

        })
        this.getProducts();
        this.checkProducts(row)
        this.open = true;
        this.submitLoading = false
        this.title = "修改用户";

      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({ value }) => {
            resetUserPwd(row.userId, value).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功，新密码是：" + value);
              }
            });
          })
          .catch(() => {});
      },
      /** 提交按钮 */
      submitForm: function () {
        console.log(this.form,'????')
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.submitLoading = true
            if (this.title === '修改用户') {
              updateUser(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.submitLoading = false
                  this.getList();
                }
              }).catch(() => this.submitLoading = false);
            } else {
              addUser(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.submitLoading = false
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.userId || this.ids;
        this.$confirm(
          '是否确认删除用户编号为"' + userIds + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delUser(userIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      },

      remove(row){
        let params = {ids:row.id};

        this.$confirm("是否删除?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return removeBatchUser(params)
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
      },

      /** 导出按钮操作 */
      handleExportDetail(id) {
        console.log(this.ids)
        const param = {ids: this.idsDetail.join(','),id:id};
        this.$confirm("是否确认导出用户数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportUserDetail(param);
          })
          .then((response) => {
            this.download(response.msg);
          })
          .catch(function () {});
      },
      /** 导出按钮操作 */
      handleExport() {
        console.log(this.ids)
        const param = {ids: this.ids.join(',')};
        this.$confirm("是否确认导出用户数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportUser(param);
          })
          .then((response) => {
            this.download(response.msg);
          })
          .catch(function () {});
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      getListData() {
        listData().then(resp => {
          let {code, data} = resp
          if (code === 200) {
            this.list = data
          }
        })
      },
      //根据数量查看具体权限
      checkProducts(row) {
        // let parm = JSON.parse(JSON.stringify(this.form))
        this.form.id = row.id
        const batchId = row.id
        getCode(batchId).then(resp => {
          let { code, data } = resp
          if(code === 200) {
            data.forEach(item => {
              this.form.productIds.push(item.productId)
            })
          }
        })
      },
      getProducts(){
          getProducts().then(resp => {
              let {code,rows} = resp;
              this.productCookieList = [{
                  id:-1,
                  code:'无'
              }];
              if(code === 200){
                  this.productCookieList = this.productCookieList.concat(rows);
              }
          })
      },
    },
  };
</script>

<style scoped>
  ul, li {
    list-style: none;
  }
</style>
